package com.navi.service.impl;

import com.navi.entity.TableEntity;
import com.navi.util.TableJdbcUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ghost on 2018/11/19.
 */
@Service
public class TableMetaService {


    @Value("${stagetable.schema}")
    private String stageTableSchema;
    @Value("${external.table.schema}")
    private String extTableSchema;
    @Value("${gpfdist.host}")
    private String gpfdistHost;
    @Value("${gpfdist.port}")
    private String gpfdistPort;
    private Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * 缓存表结构信息
     * 表结构更新需要重启对应的HMS进程
     */
    public static Map<String, TableEntity> tableMetaInfoMap = new HashMap();

    /**
     * 获取TableMeta信息
     *
     * @param tableSchema
     * @param tableName
     * @param statement
     * @return
     * @throws SQLException
     */
    public TableEntity getTableMetaInfo(String tableSchema, String tableName, Statement statement) throws SQLException {

        String tableMetaKey = tableSchema + "." + tableName;
        TableEntity tableEntity = tableMetaInfoMap.get(tableMetaKey);
        if (null == tableEntity) {
            if (stageTableSchema.equals(tableSchema)) {
                logger.info("getTableMetaInfo for stage table first time : {}.{}.", tableSchema, tableName);
                return null;
            }

            if (extTableSchema.equals(tableSchema)) {
                logger.info("getTableMetaInfo for ext table first time : {}.{}.", tableSchema, tableName);
                return null;
            }

            tableEntity = TableJdbcUtil.getTableMetaInfo(tableSchema, tableName, statement);
            tableMetaInfoMap.put(tableMetaKey, tableEntity);
            logger.info("getTableMetaInfo: {}.{}.", tableSchema, tableName);
        }

        return tableEntity;
    }

    /**
     * 直接获取表结构信息，不查询DB，调用时，程序应当已经存储信息到tableMetaInfoMap中
     *
     * @param tableSchema
     * @param tableName
     * @return
     */
    public static TableEntity getTableMetaInfo(String tableSchema, String tableName) {
        return tableMetaInfoMap.get(tableSchema + "." + tableName);
    }



    /**
     * 保存TableMeta信息
     *
     * @param tableSchema
     * @param tableName
     * @param statement
     * @throws SQLException
     */
    public void saveTableMetaInfo2Map(String tableSchema, String tableName, Statement statement) throws SQLException {
        String tableMetaKey = tableSchema + "." + tableName;
        final TableEntity tableEntity = TableJdbcUtil.getTableMetaInfo(tableSchema, tableName, statement);
        tableMetaInfoMap.put(tableMetaKey, tableEntity);
        logger.info("saveTableMetaInfo2Map: {}.{} .", tableSchema, tableName);
    }
}
